<?php

namespace app\models;

use Yii;
use yii\db\Expression;
use yii\behaviors\TimestampBehavior;

/**
 * 组织模型
 * @property int $id 主键
 * @property int $parent_id 上级
 * @property string $name 名称
 * @property string $path 层级路径
 * @property int $sort 层级路径
 * @property int $created_at 创建时间
 * @property int $updated_at 更新时间
 *
 * @property $parent
 */
class Group extends ActiveRecord
{

    public function behaviors()
    {
        return [['class' => TimestampBehavior::class]];
    }

    public function rules()
    {
        return [[['parent_id', 'name', 'sort'], 'safe']];
    }

    public function afterSave($insert, $changedAttributes)
    {
        if ($insert) {
            $this->path = $this->parent_id ? $this->getParent()->path . '_' . $this->id : $this->id;
            $this->save(false);
        }
    }

    /**
     * 组织下部门数量统计
     * @return bool|int|string|null
     */
    public function getDeptCount()
    {
        return $this->hasMany(Department::class, ['group_id' => 'id'])->count('id');
    }

    /**
     * 组织下级数量统计
     * @return bool|int|string|null
     */
    public function getChildrenCount()
    {
        return $this->hasMany(Group::class, ['parent_id' => 'id'])->count('id');
    }

    /**
     * 查询组织父级
     * @return array|\yii\db\ActiveRecord|null
     */
    public function getParent()
    {
        return self::find()->where(['id' => $this->parent_id])->one();
    }

    public static function tableName()
    {
        return '{{%group}}';
    }

    /**
     * 查询所有组织、并统计其下用户数量
     * @param int $groupId
     * @return array|\yii\db\ActiveRecord[]
     */
    public static function getListWithUserCount($groupId = 0)
    {
        // 子查询条件
        $expressionUser = new Expression('CONCAT(g.path, "%")');

        // 子查询 用户统计
        $subQuery = UserProfile::find();
        $subQuery->select('COUNT(*)');
        $subQuery->where(['like', 'u.group_path', $expressionUser]);
        $subQuery->asArray()->alias('u');

        // 组织查询
        $query = self::find();
        $query->select(['id', 'name', 'count' => $subQuery]);
        $groupId ? $query->where(['like', 'path', $groupId]) : '';
        $query->asArray()->alias('g');
        $query->orderBy('id ASC');
        return $query->all();
    }

    /**
     * 查询所有组织
     * @return array|\yii\db\ActiveRecord[]
     */
    public static function getGroupList()
    {
        $query = self::find();
        $query->select(['id', 'parent_id AS parentId', 'name']);
        $query->asArray();
        return $query->all();
    }
}
